package org.polyforms.repository.datanucleus;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.polyforms.repository.mock.MockEntity;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;

import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

public class AppEngineTestExecutionListener extends AbstractTestExecutionListener {
    private static final LocalServiceTestHelper helper = new LocalServiceTestHelper(
            new LocalDatastoreServiceTestConfig());

    @Override
    public void beforeTestClass(final TestContext testContext) throws Exception {
        helper.setUp();
        final EntityManagerFactory entityManagerFactory = testContext.getApplicationContext().getBean(
                EntityManagerFactory.class);
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            persist(entityManager, newEntity(1L, "code1", "name"));
            persist(entityManager, newEntity(2L, "code2", "name"));
            persist(entityManager, newEntity(3L, "code3", "anotherName"));
        } finally {
            entityManager.close();
        }
    }

    private void persist(final EntityManager entityManager, final MockEntity mockEntity) {
        final EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.persist(mockEntity);
        transaction.commit();
    }

    private MockEntity newEntity(final long id, final String code, final String name) {
        final MockEntity mockEntity = new MockEntity(id);
        mockEntity.setCode(code);
        mockEntity.setName(name);
        return mockEntity;
    }

    @Override
    public void afterTestClass(final TestContext testContext) throws Exception {
        helper.tearDown();
    }
}
